const app = getApp()
const WXAPI = require('../../api/newApi')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    tmplIds: { //订阅id
      type: Array,
      value: [],
    },
    cardType: { //卡类型
      type: String,
      value: '',
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowSetModel: false,
    templateIdList: [], //模版id数组
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 关闭订阅弹窗
    closeShow() {
      this.setData({
        isShow: false
      })
    },
    // 关闭提示弹窗
    sumitPropClose() {
      this.setData({
        isShowSetModel: false,
        isShow: true
      })
    },
    openSetCallback(e) {
      console.log('点击了', e)
      this.setData({
        isShowSetModel: false,
        isShow: true
      })
    },
    // 立即订阅
    sumit() {
      var that = this
      wx.requestSubscribeMessage({
        tmplIds: this.properties.tmplIds,
        success(res) {
          console.log('成功', res)
          that.data.templateIdList = []
          that.properties.tmplIds.forEach((item)=>{
            if (res[item] === 'accept') {
              //用户主动点击同意
              that.data.templateIdList.push(item)
            }
            // console.log('templateIdList++',that.data.templateIdList)
          })
          that.postSubscriptionScuess()
        },
        fail(res) {
          // 20004:用户关闭了主开关，无法进行订阅,引导开启
          if (res.errCode == 20004) {
            // 显示引导设置弹窗
            that.setData({
              isShowSetModel: true,
              isShow: false
            })
          } else {
            wx.showModal({
              title: res.errCode,
              content: res.errMsg,
              showCancel: false
            })
          }
          console.log('失败', res)
        },
      })
    },
    // 订阅成功请求
    postSubscriptionScuess() {
      var data = {
        appId: app.globalData.appid,
        paySource: app.globalData.paySource,
        cardType: this.properties.cardType,
        templateIdList: this.data.templateIdList
      }
      WXAPI.subscriptionScuess(data, (res) => {
        if (res.code == 200) {
          this.setData({
            isShow: false
          })
        }
        wx.hideLoading()
      })
    },
  }
})